<template>
  <view class="scan-container">
    <!-- 顶部标题栏 -->
    <view class="header">
      <cover-view class="title">扫码充电</cover-view>
      <cover-view class="subtitle">请对准充电枪上的二维码</cover-view>
    </view>

    <!-- 模拟扫码区域 -->
    <view class="scan-area">
      <view class="scan-box">
        <view class="scan-frame">
          <view class="corner top-left"></view>
          <view class="corner top-right"></view>
          <view class="corner bottom-left"></view>
          <view class="corner bottom-right"></view>
        </view>
        <view class="scan-line"></view>
      </view>
      <cover-view class="scan-tip">将二维码放入框内，自动扫描</cover-view>
    </view>

    <!-- 充电枪信息卡片 -->
    <view class="gun-card" v-if="showGunInfo">
      <view class="gun-header">
        <image src="/static/gun-icon.png" class="gun-icon"></image>
        <cover-view class="gun-name">充电枪 #{{gunNumber}}</cover-view>
        <view class="gun-status" :class="{'available': gunStatus === 0, 'busy': gunStatus === 1}">
          {{gunStatus === 0 ? '空闲' : '使用中'}}
        </view>
      </view>
      <view class="divider"></view>
      <view class="gun-details">
        <view class="detail-item">
          <image src="/static/power-icon.png" class="detail-icon"></image>
          <view class="detail-text">
            <cover-view class="label">功率</cover-view>
            <cover-view class="value">60kW</cover-view>
          </view>
        </view>
        <view class="detail-item">
          <image src="/static/voltage-icon.png" class="detail-icon"></image>
          <view class="detail-text">
            <cover-view class="label">电压</cover-view>
            <cover-view class="value">200-750V</cover-view>
          </view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <!-- 修改后的按钮结构 -->
    <view class="action-btns">
      <button class="scan-btn primary" @click="verifyBalance" :disabled="checkingBalance">
        <view class="btn-inner">
          <image src="/static/scan-icon-white.png" class="btn-icon"></image>
          <cover-view class="btn-text">{{checkingBalance ? '检查中...' : '扫码充电'}}</cover-view>
        </view>
      </button>
      <button class="scan-btn secondary" @click="showManualInput">
        <view class="btn-inner">
          <image src="/static/input-icon-green.png" class="btn-icon"></image>
          <cover-view class="btn-text">手动输入编号</cover-view>
        </view>
      </button>
    </view>

    <!-- 倒计时弹窗 -->
    <zwy-popup :ishide='isshow' width="600rpx" height="400rpx" radius="24rpx">
      <view class="popup-content">
        <image src="/static/connecting.png" class="popup-image"></image>
        <cover-view class="popup-title">正在连接充电枪</cover-view>
        <view class="countdown-display">
          <cover-view class="countdown-number">{{countdown}}</cover-view>
          <cover-view class="countdown-unit">秒</cover-view>
        </view>
        <cover-view class="popup-tip">请保持手机靠近充电枪</cover-view>
        <view class="progress-bar">
          <view class="progress" :style="{width: (100 - countdown * 100 / 60) + '%'}"></view>
        </view>
      </view>
    </zwy-popup>

    <!-- 操作指引 -->
    <view class="guide-section">
      <view class="section-header">
        <cover-view class="section-title">操作指引</cover-view>
        <image src="/static/guide-icon.png" class="section-icon"></image>
      </view>
      <view class="guide-steps">
        <view class="step">
          <cover-view class="step-number">1</cover-view>
          <cover-view class="step-text">扫描充电枪上的二维码</cover-view>
        </view>
        <view class="step">
          <cover-view class="step-number">2</cover-view>
          <cover-view class="step-text">确认充电枪信息</cover-view>
        </view>
        <view class="step">
          <cover-view class="step-number">3</cover-view>
          <cover-view class="step-text">开始充电</cover-view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isshow: false,
      userId: "",
      pileId: "",
      gunId: "",
      billId: "",
      countdown: 60,
      showGunInfo: false,
      gunNumber: 'A12',
      gunStatus: 0,
	  checkingBalance: false,
	  connectionSuccess: false
    }
  },
  onShow() {
    this.userId = uni.getStorageSync("userId")
  },
  methods: {
    async verifyBalance() {
        if (this.checkingBalance) return;
        
        this.checkingBalance = true;
        try {
          let userId = uni.getStorageSync("userId")
          if (!userId) {
            uni.showToast({ title: "请先登录", icon: "none" })
            return
          }
          
          const res = await uni.request({
            url: this.$baseUrl + "/user_api/user/balance/" + userId,
            method: "GET"
          })
          console.log(res)
          let balance = res.data.data.balance
		  console.log(balance)
          if (balance < 10) {
            uni.showModal({
              content: "余额不足10元，请先充值",
              confirmText: "去充值",
              success: (res) => {
                if (res.confirm) {
                  uni.navigateTo({ url: "/pages/myWallet/myWallet" })
                }
              }
            })
            return
          }
          
          this.scan()
        } catch (err) {
          uni.showToast({ title: "获取余额失败", icon: "none" })
        } finally {
          this.checkingBalance = false;
        }
      },
    createBill() {
          let billParam = {
            userId: this.userId,
            pileId: this.pileId,
            gunId: this.gunId
          }
          uni.showLoading({
            title: '创建订单中...',
            mask: true
          })
          
          uni.request({
            url: this.$baseUrl + "/order_api/order/create",
            method: "POST",
            data: billParam,
            success: (res) => {
              uni.hideLoading()
              
              // 严格检查返回结果
              if(res.data && res.data.code === 0) {
                // 真正成功的逻辑
                this.billId = res.data.data
                uni.setStorageSync("billId", this.billId)
                
                // 创建成功立即跳转
                uni.navigateTo({
                  url: `/pages/chargingProgress/chargingProgress?billId=${this.billId}&gunId=${this.gunId}`
                })
                
                // 关闭弹窗
                this.isshow = false
              } else {
                // 业务逻辑失败处理
                let errorMsg = res.data?.msg || '创建订单失败'
                uni.showToast({
                  title: errorMsg,
                  icon: 'none',
                  duration: 3000
                })
                this.isshow = false
              }
            },
            fail: (err) => {
              uni.hideLoading()
              // HTTP请求失败处理
              uni.showToast({
                title: '网络错误，请检查连接',
                icon: 'none',
                duration: 3000
              })
              this.isshow = false
              
              // 调试用
              console.error('创建订单请求失败:', err)
            },
            complete: () => {
              // 无论成功失败都清除倒计时
              clearInterval(this.timer)
            }
          })
        },
        
        scan() {
          let that = this
          that.countdown = 60
          that.isshow = true
          
          // 设置超时定时器
          this.timer = setInterval(() => {
            if(that.countdown <= 0) {
              clearInterval(that.timer)
              that.isshow = false
              if(!that.billId) {
                uni.showToast({
                  title: "连接超时，请重试",
                  icon: "none"
                })
              }
              return
            }
            that.countdown--
          }, 1000)
          
          // 模拟扫码成功
          uni.scanCode({
            scanType: ['qrCode'],
            success: function(res) {
              let result = res.result
              try {
                let deviceInfo = JSON.parse(result)
                that.pileId = deviceInfo.pileId
                that.gunId = deviceInfo.gunId
                that.showGunInfo = true
                that.gunNumber = that.gunId
                
                // 开始创建订单
                that.createBill()
              } catch(e) {
                clearInterval(that.timer)
                that.isshow = false
                uni.showToast({
                  title: "二维码格式错误",
                  icon: "none"
                })
              }
            },
            fail: (err) => {
              clearInterval(this.timer)
              this.isshow = false
              uni.showToast({
                title: "扫码失败: " + (err.errMsg || '未知错误'),
                icon: "none"
              })
            }
          })
        },
    showManualInput() {
      uni.showToast({
        title: '手动输入功能开发中',
        icon: 'none'
      });
    }
  }
}
</script>

<style>
/* 基础样式 */
page {
  background-color: #f8f8f8;
}/* 全局容器样式 */
.scan-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 30rpx;
}

/* 顶部标题栏 */
.header {
  text-align: center;
  margin-bottom: 40rpx;
}
.title {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}
.subtitle {
  font-size: 28rpx;
  color: #999;
}

/* 扫码区域 */
.scan-area {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.scan-box {
  width: 400rpx;
  height: 400rpx;
  position: relative;
  margin-bottom: 30rpx;
  border: 2rpx solid #f0f0f0;
}

.scan-frame {
  width: 100%;
  height: 100%;
  position: relative;
}

/* 扫码框四角样式 */
.corner {
  position: absolute;
  width: 40rpx;
  height: 40rpx;
  border-color: #07c160;
  border-style: solid;
  border-width: 0;
}
.top-left {
  top: 0;
  left: 0;
  border-top-width: 6rpx;
  border-left-width: 6rpx;
}
.top-right {
  top: 0;
  right: 0;
  border-top-width: 6rpx;
  border-right-width: 6rpx;
}
.bottom-left {
  bottom: 0;
  left: 0;
  border-bottom-width: 6rpx;
  border-left-width: 6rpx;
}
.bottom-right {
  bottom: 0;
  right: 0;
  border-bottom-width: 6rpx;
  border-right-width: 6rpx;
}

/* 扫描线动画 */
.scan-line {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4rpx;
  background: linear-gradient(to right, transparent, #07c160, transparent);
  animation: scan 2s linear infinite;
}

@keyframes scan {
  0% { top: 0; opacity: 0; }
  10% { opacity: 1; }
  90% { opacity: 1; }
  100% { top: 100%; opacity: 0; }
}

.scan-tip {
  font-size: 28rpx;
  color: #666;
}

/* 充电枪信息卡片 */
.gun-card {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.gun-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.gun-icon {
  width: 50rpx;
  height: 50rpx;
  margin-right: 20rpx;
}

.gun-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
}

.gun-status {
  font-size: 26rpx;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
}
.gun-status.available {
  background-color: #e1f5e8;
  color: #07c160;
}
.gun-status.busy {
  background-color: #ffebee;
  color: #f44336;
}

.divider {
  height: 1rpx;
  background-color: #eee;
  margin: 20rpx 0;
}

.gun-details {
  display: flex;
  justify-content: space-between;
}

.detail-item {
  display: flex;
  align-items: center;
  width: 48%;
}

.detail-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 15rpx;
}

.detail-text {
  display: flex;
  flex-direction: column;
}

.label {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 5rpx;
}

.value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

/* 操作按钮容器 */
.action-btns {
  display: flex;
  flex-direction: column;
  margin-top: 40rpx;
}

/* 按钮通用样式 */
.scan-btn {
  height: 100rpx; /* 固定高度确保一致 */
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  font-size: 32rpx;
  margin-bottom: 30rpx;
  border: none;
  padding: 0 40rpx; /* 增加左右内边距 */
  position: relative;
  overflow: hidden;
}

/* 主按钮样式 */
.scan-btn.primary {
  background: linear-gradient(to right, #07c160, #09d168);
  color: white;
}

/* 次按钮样式 */
.scan-btn.secondary {
  background-color: white;
  border: 1rpx solid #07c160;
  color: #07c160;
}

/* 按钮内部容器 */
.btn-inner {
  display: flex;
  align-items: center;
  width: 100%;
}


.scan-btn:disabled {
  opacity: 0.7;
}


/* 图标样式（左对齐） */
.btn-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 20rpx; /* 图标和文字间距 */
}

/* 文字样式（居中对齐） */
.btn-text {
  flex: 1;
  text-align: center;
  transform: translateX(-20rpx); /* 补偿图标宽度，实现视觉居中 */
}

/* 弹窗样式 */
.popup-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 40rpx;
}

.popup-image {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 30rpx;
  object-fit: contain;
}

.popup-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.countdown-display {
  display: flex;
  align-items: baseline;
  margin-bottom: 30rpx;
}

.countdown-number {
  font-size: 60rpx;
  font-weight: bold;
  color: #07c160;
  margin-right: 10rpx;
}

.countdown-unit {
  font-size: 28rpx;
  color: #999;
}

.popup-tip {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 30rpx;
}

.progress-bar {
  width: 100%;
  height: 8rpx;
  background-color: #eee;
  border-radius: 4rpx;
  overflow: hidden;
}

.progress {
  height: 100%;
  background: linear-gradient(to right, #07c160, #09d168);
  transition: width 1s linear;
}

/* 操作指引 */
.guide-section {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-top: 40rpx;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
}

.section-icon {
  width: 40rpx;
  height: 40rpx;
}

.guide-steps {
  display: flex;
  flex-direction: column;
}

.step {
  display: flex;
  align-items: center;
  margin-bottom: 25rpx;
}

.step-number {
  width: 40rpx;
  height: 40rpx;
  background-color: #07c160;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
  font-size: 24rpx;
}

.step-text {
  font-size: 28rpx;
  color: #666;
}
</style>